package com.tongsys.server.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tongsys.server.entity.User;
import com.tongsys.server.utils.JwtUtils;
import com.tongsys.server.utils.RtnCode;
import com.tongsys.server.utils.RtnUtils;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
@ApiModel("登录认证成功 处理器类")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //设置响应的编码格式, 返回 json 格式
        response.setContentType("application/json;charset=utf-8");
        //获取当前登录用户的信息
        User user = (User) authentication.getPrincipal();
        //获取token
        String token = jwtUtils.createToken(user.getId());
        //组装返回信息
        RtnUtils res = RtnUtils.ok().code(RtnCode.SUCCESS).data(token);
        //将对象转换成json根式,并消除循环引用（主要要消除循环引用）
        String result = JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect);

        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //以UTF-8格式输出数据
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        //关闭流
        outputStream.flush();
        outputStream.close();
    }
}
